package com.example.testdb3.controller;

import com.example.testdb3.entiry.UserInfo;
import com.example.testdb3.entiry.dto.UserInfoPageDto;
import com.example.testdb3.entiry.vo.UserInfoVo;
import com.example.testdb3.mapper.UserMapper;
import com.example.testdb3.result.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/add")
    public Result add(@RequestBody UserInfo userInfo) {
        if (userInfo.getCreateTime() == null) {
            userInfo.setCreateTime(LocalDateTime.now());
        }
        userMapper.add(userInfo);

        String message = "添加成功，添加的sid为" + userInfo.getId();
        return Result.success(message);
    }

    @GetMapping("/list")
    public Result<List<UserInfo>> list() {

        List<UserInfo> userInfoList = userMapper.list();

        return Result.success(userInfoList);
    }

    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable Long id){

        userMapper.delete(id);
        return Result.success("删除成功");
    }


    @PutMapping("/update")
    public Result<String> update(@RequestBody UserInfo userINfo) {

        userMapper.update(userINfo);

        return Result.success("修改成功");
    }

    @GetMapping("/page")
    public Result<UserInfoVo> query(
            // @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime start,
            // @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end
            UserInfoPageDto userInfoPageDto
    ) {
        // System.out.println("接收到的数据为+++++++" + start + end);
        // if (start == null && end == null) {
        //     return "数据接收异常";
        // } else {
        //     return "数据接收成功";
        // }

        // System.out.println("接收到的参数为" + userInfoPageDto);
        // if (ObjectUtils.isEmpty(userInfoPageDto)) {
        //     return "接收到的参数为空";
        // } else {
        //     return "接收成功";
        // }
        //分页
        System.out.println(userInfoPageDto);
        PageHelper.startPage(userInfoPageDto.getPageNum(), userInfoPageDto.getPageSize());
        Page<UserInfo> page = userMapper.pageUserInfos(userInfoPageDto.getStartTime(), userInfoPageDto.getEndTime());
        return Result.success(new UserInfoVo(page.getTotal(), page.getResult()));
    }
}
